/*
  Timer goes a step every 1 second.

*/
Timer = function(capture, db, memo){
  this.running = false;
  this.taskSelect = $('#tasks');
  this.btn = $("#startBtn");
  this.hourLabel = $("#hour");
  this.minuteLabel = $("#minute");
  this.secondLabel = $("#second");
  this.secondsAccumulated = 0;   // an accumulated value
  this.seconds = 0;   // init per start
  this.startAt = null;  // init per start
  this.capture = capture;
  this.db = db;
  this.memo = memo;
};

Timer.prototype.startOrStop = function(){
  if(this.running === false){
    this.running = true;
    this.btn.disabled = false;
    this.start();
    this.btn.className = 'stop';
    this.taskSelect.disabled = true;
    this.btn.disabled = true;
  }else{
    this.running = false;
    this.btn.disabled = false;
    this.stop();
    this.btn.className = 'start';
    this.taskSelect.disabled = false;
    this.btn.disabled = true;
  }
};

Timer.prototype.start = function(){
  //get task id
  this.taskId = $('#tasks').value;
  
  // 0 second
  this.seconds = 0;
  this.startAt = new Date().getTime();
  this.on1sec();
  this.capture.start(this.taskId);
  
  // update memo;
  this.updateMemo(this.startAt);
  
  // from 1 second, step 1 second
  var me = this;
  this.tickId = setInterval(function(){
    me.seconds ++;
    me.secondsAccumulated ++;
    me.on1sec();
  }, 1000);
};

Timer.prototype.updateMemo = function(startAt){
  if(this.running === true){
    var comment = $('#view').textContent;
    if(comment){
      var rec = {
        id: startAt,
        taskId: this.taskId,
        start: startAt,
        comment: comment
      };
      this.memo.commit(rec);
    }
  }
};

Timer.prototype.stop = function(){
  this.save();
  this.db.push(); //sync hours after stop
  clearInterval(this.tickId);
  this.capture.stop();
};

/*
  Handler for every minute
*/
Timer.prototype.on1sec = function(){
  this.updateUI();
  
  if(this.seconds % 60 === 0){
      this.save();
  }
};

Timer.prototype.save = function(){
  //save to db
  var rec = {
    id: this.startAt,
    taskId: this.taskId,
    start: this.startAt,
    seconds: this.seconds
  };
  this.db.commit(rec);
};

/*
  Update UI of timer
*/
Timer.prototype.updateUI = function(){
  var s = 0,
      m = 0,
      h = 0;
  s = this.seconds % 60;
  var minutes = (this.seconds - s) / 60;
  m = minutes % 60;
  h = (minutes - m) / 60;
  if(s < 10){
    s = '0' + s;
  }
  if(m < 10){
    m = '0' + m;
  }
  if(h < 10){
    h = '0' + h;
  }
  this.hourLabel.textContent = h;
  this.minuteLabel.textContent = m;
  this.secondLabel.textContent = s;
};